import { ChangeEvent, ChangeEventHandler, Fragment, ReactElement, SetStateAction, useEffect, useRef, useState } from "react";
import lessModule from "./index.module.less"
import closeImage from "../../../../../../assets/image/homePage-close.png"
import searchImage from "../../../../../../assets/image/homePage-search.png"
import { Button, Input } from "antd";
import { modeType } from "../../../../../../common/interface";
import { $Http } from "../../../../../../network";
import { $eventBus } from "../../../../../../common/utils";
import HomePage_DateTimePickerRangeComponent from "../../../dateTimePickerRange";
import HomePage_TagComponent from "../../../tag";
import HomePage_ModalComponent_SelectMonitorModalComponent_SelectNestedComponent from "./component/selectNested";
import { json } from "stream/consumers";



// 主页-选择监测弹窗组件
interface componentInterface {
    isCard?: boolean
    modalName?: string
    operation?: string
    monitoringType: string
    stationData?: object
    mode: modeType
    selectedList?: Array<string>
    selectedOtherList?: Array<object>
    isDateTimePickerRange?: boolean
    change_selectedOtherList?: Function
    click_cancel?: Function
}

const HomePage_ModalComponent_SelectMonitorModalComponent: React.FC<componentInterface> = (props) => {

    const tabList = ["全部展开", "全部折叠"]
    const isInit = useRef<boolean>(true)
    const isCardRef = useRef<boolean>(false)
    const [isCard, setIsCard] = useState<boolean>(false)
    const [sourceList, setSourceList] = useState<Array<object>>([])
    const [searchText, setSearchText] = useState<string>("")
    const [tabIdx, setTabIdx] = useState<number>(0)
    const [selectedList, setSelectedList] = useState<Array<string>>(props.selectedList ?? [])
    const [selectedOtherList, setSelectedOtherList] = useState<Array<object>>(props.selectedOtherList ?? [])
    const change_search = (event: ChangeEvent) => {
        setSearchText(event["target"]["value"])
    }
    
    const click_tabItem = (idx: number) => {
        setTabIdx(idx)
    }
    
    const http_search = () => {
        $Http("search", { typeName: `${props.operation ?? "安装"}${props.monitoringType}`, keyword: searchText, ...(Object.keys(props.stationData ?? {}).length ? { stationID: props.stationData?.["id"], maintainCentre: props.stationData?.["maintainCentre"] } : {}) }).then((res) => {;
            setSourceList([...(props.monitoringType === "站点" ? res : res["data"])["list"]])
        })
    }
    
    const click_del = (idx: number) => {
        setSelectedList([...selectedList.filter((_: string, itemIdx: number) => itemIdx !== idx)])
        setSelectedOtherList([...selectedOtherList.filter((_: object, itemIdx: number) => itemIdx !== idx)])
    }
    const change_selectedOtherList = (list: Array<object>) => {
        props.change_selectedOtherList?.(list)
        setSelectedOtherList([...list])
    }
    const click_submit = () => {
        setTimeout(() => {
            $eventBus.emit("selectMonitorModalSelectedList", { source: "HomePage_ModalComponent_SelectMonitorModalComponent", explain: "选择监测弹窗中，已经选中的监测列表", data: { mode: props.mode, selectedList, selectedOtherList } })
            props.click_cancel?.()
        });
    }
    
    // 搜索框防抖
    useEffect(() => {
        const antiShakeTimeout = setTimeout(() => {
            !isInit.current && http_search()
            isInit.current = false
        }, 300);
        return () => {
            clearTimeout(antiShakeTimeout);
        };
    }, [searchText])
    
    
    useEffect(() => {
        !props.selectedList && setSelectedList([])
        !props.selectedOtherList && setSelectedOtherList([])
        http_search()
    }, [props.monitoringType])

    useEffect(() => {
        isCardRef.current = !!props.isCard
        setIsCard(isCardRef.current)
    }, [])
    return (
        <div className={lessModule["homePageModalComponentSelectMonitorModalComponent"]}>
            {
                !props.isCard && <header className={lessModule["homePageModalComponentSelectMonitorModalComponent-header"]}>
                    <span>{props.modalName}</span>
                    <img className="homePage-handleImage" src={closeImage} onClick={() => props.click_cancel?.()} />
                </header>
            }
            <main className={lessModule["homePageModalComponentSelectMonitorModalComponent-main"]} style={{ padding: !props.isCard ? " 7px 24px 0" : 0 }}>
                <div className={lessModule["homePageModalComponentSelectMonitorModalComponent-main__left"]} style={{ width: !props.isCard ? 480 : "100%" }}>
                    {
                        !props.isCard && <span>选择</span>
                    }
                    <div className={lessModule["homePageModalComponentSelectMonitorModalComponent-main__card"]} style={{ height: props.isCard ? "fit-content" : 380 }}>
                        {
                            props.isDateTimePickerRange && <HomePage_DateTimePickerRangeComponent width="100%" />
                        }
                        {
                            !props.isDateTimePickerRange && <Input placeholder="请输入搜索关键字" autoComplete="off" suffix={<img src={searchImage} />} onChange={change_search} />
                        }

                        <div className={lessModule["main-card__operation"]}>
                            <div className={lessModule["card-operation__tab"]}>
                                {
                                    tabList.map((item, idx) => {
                                        return (
                                            <span key={`tabItem${idx}`} className={lessModule["operation-tab__name"]} style={{ color: idx === tabIdx ? "#1890FF" : "rgba(0, 0, 0, 0.45)" }} onClick={() => click_tabItem(idx)}>{item}</span>
                                        )
                                    })
                                }
                            </div>
                            {
                                props.isCard && selectedList.length > 0 && <div className={lessModule["card-operation__selected"]}>
                                    <span>已选：</span>
                                    <HomePage_TagComponent name={selectedList[0]} />
                                </div>
                            }
                        </div>

                        <div style={{ overflowY: !props.isCard ? "scroll" : "visible" }}>
                            <HomePage_ModalComponent_SelectMonitorModalComponent_SelectNestedComponent
                                isCard={isCard} monitoringType={props.monitoringType} mode={props.mode} isOpen={!tabIdx} sourceList={sourceList} selectedList={selectedList} selectedOtherList={selectedOtherList} change_selectedList={setSelectedList} change_selectedOtherList={change_selectedOtherList} />
                        </div>

                    </div>
                </div>
                {
                    !props.isCard && <div className={lessModule["homePageModalComponentSelectMonitorModalComponent-main__right"]}>
                        <span>已选{props.mode === "multiple" && `（${selectedList.length}/5）`}</span>
                        <div className={`${lessModule["homePageModalComponentSelectMonitorModalComponent-main__card"]} ${lessModule["main-right__card"]}`} style={{ height: props.isCard ? "fit-content" : 380 }}>
                            {
                                selectedList.map((item, idx) => (
                                    <Fragment key={`selectedItem${idx}`}>
                                        <HomePage_TagComponent name={item} click_del={() => click_del(idx)} />
                                    </Fragment>
                                ))
                            }
                        </div>
                    </div>
                }
            </main>
            {
                !props.isCard && <footer className={lessModule["homePageModalComponentSelectMonitorModalComponent-footer"]}>
                    <Button className={lessModule["homePageModalComponentSelectMonitorModalComponent-footer__btn"]} type="primary" ghost onClick={() => props.click_cancel?.()}>取消</Button>
                    <Button className={lessModule["homePageModalComponentSelectMonitorModalComponent-footer__btn"]} type="primary" onClick={() => click_submit()}>确定</Button>
                </footer>
            }
        </div>
    )
}



export default HomePage_ModalComponent_SelectMonitorModalComponent